import Taro, { navigateTo } from "@tarojs/taro";
import createPromise from "../create-promise";
import { store } from "@/store";
import { instance as Log } from "@/lib/log";
import { log } from "console";

function createFetchHandler(config?: Record<string, unknown>) {
  return async function (options: any): Promise<any> {
    const promise = createPromise();
    const data = options.data ?? ((options.params as any) || {});
    const {
      user: { auth },
    } = store.getState();
    let _headers;
    if (auth.token) {
      _headers = {
        Authorization: JSON.stringify({ token: auth.token }),
      };
    }

    let url;
    if (options.url.startsWith("http")) {
      url = options?.url;
    } else {
      url = options.prefix
        ? options.prefix + options.url
        : process.env.SERVER_HOST + options?.url || "";
    }

    Taro.request({
      ...options,
      url,
      method: (options.method as any) || "GET",
      data,
      headers: {
        ...options.headers,
        ..._headers,
      },
      timeout: 60000,
      ...config,
      success(res) {
        if (
          typeof res === "string" ||
          res?.data?.code === "0" ||
          res?.data?.status ||
          res?.data?.success
        ) {
          promise.resolve(res?.data);
        } else if (res?.data?.code === "A0230") {
          Taro.showToast({
            title: res?.data.msg || "登录状态失效，请重新登录",
            icon: "none",
            duration: 2000,
          });
          // setTimeout(() => {
          //   navigateTo({
          //     url: "/sub_common/pages/auth/index",
          //   });
          // }, 2000);
          promise.reject(res?.data);
        } else {
          promise.reject(res?.data);
        }
      },
      fail(error) {
        Log.error("taro request 失败error", error);
        Taro.hideLoading();
        promise.reject(error);
      },
    });
    return await promise;
  };
}

export const request = createFetchHandler();

export default createFetchHandler;
